package com.astn.bks;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import com.astn.adapter.booking.PBedAdapter;
import com.astn.adapter.booking.PFacilityAdapter;
import com.astn.bks.util.BksConstants;
import com.astn.bks.util.BksState;
import com.astn.bks.util.JsonUtils;
import com.astn.bks.util.WebserviceUtils;
import com.astn.components.ActionItem;
import com.astn.components.QuickAction;
import com.astn.components.QuickAction.OnActionItemClickListener;
import com.astn.entity.booking.QuoteBed;
import com.astn.entity.booking.QuoteFacility;
import com.astn.entity.booking.QuoteOffer;
import com.astn.entity.booking.QuoteRequest;
import com.astn.entity.booking.QuoteRoomType;

import adstn.dialoglib.Dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.Toast;

public class PPostOffer extends Activity {

	private ArrayList<QuoteBed> lstBeds = new ArrayList<QuoteBed>();
	private ArrayList<QuoteFacility> lstFacilities = new ArrayList<QuoteFacility>();
	private ArrayList<Boolean> lstIsBedNull = new ArrayList<Boolean>();
	private ArrayList<Boolean> lstIsFacilityNull = new ArrayList<Boolean>();
	private List<QuoteRoomType> lstRoomType = new Vector<QuoteRoomType>();
	private RatingBar rtbQuality;
	private EditText txtPrice;
	private Spinner spnRoomType;
	private ListView lsvBeds;
	private ListView lsvFacilities;
	private Button btnPostOffer;
	private Button btnCancel;
	private LinearLayout layBeds;
	private LinearLayout layFacilities;
	private QuickAction bedQuickAction;
	private QuickAction facilityQuickAction;
	private ActionItem aiAdd;
	private ActionItem aiEdit;
	private ActionItem aiDelete;
	private ActionItem aiClear;
	private QuoteBed currentBed;
	private int lsvBedSelectPos;
	private int lsvFacilitiesSelectPos;
	private QuoteOffer currentOffer = new QuoteOffer();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.postoffer);
		rtbQuality = (RatingBar) findViewById(R.id.ratQuality);
		txtPrice = (EditText) findViewById(R.id.txtPrice);
		spnRoomType = (Spinner) findViewById(R.id.spnRoomType);
		layBeds = (LinearLayout) findViewById(R.id.layBeds);
		lsvBeds = (ListView) findViewById(R.id.lsvBeds);
		layFacilities = (LinearLayout) findViewById(R.id.layFacilities);
		lsvFacilities = (ListView) findViewById(R.id.lsvFacilities);
		btnPostOffer = (Button) findViewById(R.id.btnPostOffer);
		btnCancel = (Button) findViewById(R.id.btnCancel);
		bedQuickAction = new QuickAction(this);
		aiAdd = new ActionItem(BksConstants.ADD, "", getResources()
				.getDrawable(R.drawable.ic_add));
		aiEdit = new ActionItem(BksConstants.EDIT, "", getResources()
				.getDrawable(R.drawable.ic_edit));
		aiDelete = new ActionItem(BksConstants.DELETE, "", getResources()
				.getDrawable(R.drawable.ic_delete));
		aiClear = new ActionItem(BksConstants.CLEAR, "", getResources()
				.getDrawable(R.drawable.ic_delete));
		// Get listRoomType from server
		Object rsObj = null;

		try {
			rsObj = WebserviceUtils.call("com_xmlrpc", "getListRoomType", null);
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (rsObj != null) {
			QuoteRoomType[] arrRs = null;
			try {
				arrRs = JsonUtils.gson.fromJson((String) rsObj,
						QuoteRoomType[].class);
			} catch (Exception e) {
				e.printStackTrace();
			}
			lstRoomType = new Vector<QuoteRoomType>();
			if (arrRs != null) {
				lstRoomType.addAll(Arrays.asList(arrRs));
			}
			ArrayAdapter<QuoteRoomType> adapRoomType = new ArrayAdapter<QuoteRoomType>(
					this, android.R.layout.simple_spinner_item, lstRoomType);
			adapRoomType
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spnRoomType.setAdapter(adapRoomType);

		}
		lsvBeds.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0) {
					lsvBed1Click();
				} else {
					lsvBedSelectPos = position;
					lsvBedNClick();
				}
			}

		});
		lstBeds = new ArrayList<QuoteBed>();
		lstIsBedNull = new ArrayList<Boolean>();
		lstFacilities = new ArrayList<QuoteFacility>();
		lstIsFacilityNull = new ArrayList<Boolean>();
		PBedAdapter bedAdap = new PBedAdapter(getApplicationContext(), lstBeds);
		lsvBeds.setAdapter(bedAdap);

		lsvFacilities.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0) {
					lsvFacilities1Click();
				} else {
					lsvFacilitiesSelectPos = position;
					lsvFacilitiesNClick();
				}
			}

		});
		PFacilityAdapter facilityAdap = new PFacilityAdapter(
				getApplicationContext(), lstFacilities);

		lsvFacilities.setAdapter(facilityAdap);
		Intent i = getIntent();
		QuoteRequest request = (QuoteRequest) i
				.getSerializableExtra(BksConstants.EXTRA_REQUEST);
		if (request == null) {
			setResult(BksConstants.RESULT_ERROR);
			finish();
		} else {
			currentOffer.setAdult(request.getAdult());
			currentOffer.setChildren(request.getChildren());
			currentOffer.setCountry(request.getCountry());
			currentOffer.setFrom(request.getFrom());
			currentOffer.setFrom_user(WebserviceUtils.getUser().getId());
			currentOffer.setOffer_status(BksState.Offer.CREATED);
			int regionid = 0;
			try {
				regionid = Integer.parseInt(request.getRegion());
			} catch (Exception e) {
				// TODO: handle exception
			}
			currentOffer.setRegion(regionid);
			currentOffer.setRequest_id(request.getId());

			currentOffer.setState(request.getState());
			currentOffer.setTo(request.getTo());
			currentOffer.setTo_user(request.getUserid());
			int townid = 0;
			try {
				townid = Integer.parseInt(request.getTown());
			} catch (Exception e) {
				// TODO: handle exception
			}
			currentOffer.setTown(townid);
			String currentOfferStr = JsonUtils.gson.toJson(currentOffer);
			// System.out.println(currentOfferStr);
		}
		btnPostOffer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String errMsg = parseInfo();
				if (errMsg.length() > 0) {
					Toast.makeText(PPostOffer.this, errMsg, Toast.LENGTH_SHORT)
							.show();
				} else {
					Map<String, Object> mapPara = new HashMap<String, Object>();
					mapPara.put("OFFER", JsonUtils.gson.toJson(currentOffer));
					try {
						WebserviceUtils
								.call("com_xmlrpc", "postOffer", mapPara);
						Toast.makeText(PPostOffer.this, "Success",
								Toast.LENGTH_SHORT).show();
						setResult(RESULT_OK);
						finish();
					} catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(PPostOffer.this, "Webservice error.",
								Toast.LENGTH_SHORT).show();
					}
				}
			}

		});
	}

	private void lsvBed1Click() {
		bedQuickAction = new QuickAction(this);
		bedQuickAction.addActionItem(aiAdd);
		bedQuickAction.addActionItem(aiClear);
		bedQuickAction
				.setOnActionItemClickListener(new BedActionItemSelectedListener());
		bedQuickAction.show(lsvBeds);
	}

	private void lsvFacilities1Click() {
		facilityQuickAction = new QuickAction(this);
		facilityQuickAction.addActionItem(aiAdd);
		facilityQuickAction.addActionItem(aiClear);
		facilityQuickAction
				.setOnActionItemClickListener(new FacilityActionItemSelectedListener());
		facilityQuickAction.show(lsvFacilities);

	}

	private void lsvBedNClick() {
		bedQuickAction = new QuickAction(this);
		bedQuickAction.addActionItem(aiAdd);
		bedQuickAction.addActionItem(aiEdit);
		bedQuickAction.addActionItem(aiDelete);
		bedQuickAction
				.setOnActionItemClickListener(new BedActionItemSelectedListener());
		bedQuickAction.show(lsvBeds);

	}

	private void lsvFacilitiesNClick() {
		facilityQuickAction = new QuickAction(this);
		facilityQuickAction.addActionItem(aiAdd);
		facilityQuickAction.addActionItem(aiDelete);
		facilityQuickAction
				.setOnActionItemClickListener(new FacilityActionItemSelectedListener());
		facilityQuickAction.show(lsvFacilities);

	}

	private class BedActionItemSelectedListener implements
			OnActionItemClickListener

	{

		@Override
		public void onItemClick(QuickAction source, int pos, int actionId) {
			switch (actionId) {
			case BksConstants.ADD:
				Intent iA = new Intent(PPostOffer.this, DiaBed.class);
				iA.putExtra(BksConstants.EXTRA_STATE, BksConstants.ADD);
				startActivityForResult(iA, BksConstants.REQUEST_ADD_BED);
				break;
			case BksConstants.EDIT:
				Intent iE = new Intent(PPostOffer.this, DiaBed.class);
				iE.putExtra(BksConstants.EXTRA_STATE, BksConstants.EDIT);
				if (lsvBedSelectPos > 0) {
					iE.putExtra(BksConstants.EXTRA_BED,
							lstBeds.get(lsvBedSelectPos - 1));
					startActivityForResult(iE, BksConstants.REQUEST_EDIT_BED);
				}
				break;
			case BksConstants.DELETE:
				if (lsvBedSelectPos > 0) {
					lstBeds.remove(lsvBedSelectPos - 1);
					PBedAdapter bedAdap = new PBedAdapter(
							getApplicationContext(), lstBeds);
					lsvBeds.setAdapter(bedAdap);
				}
				break;
			case BksConstants.CLEAR:
				AlertDialog dialog = Dialog.getYesNoDialog(PPostOffer.this,
						"Do you really want to clear?");
				dialog.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface dialog) {
						clearBeds();
					}
				});
				dialog.show();
				break;
			default:
				break;
			}

		}

	}

	private class FacilityActionItemSelectedListener implements
			OnActionItemClickListener

	{

		@Override
		public void onItemClick(QuickAction source, int pos, int actionId) {
			switch (actionId) {
			case BksConstants.ADD:
				Intent iA = new Intent(PPostOffer.this, DiaFacility.class);
				iA.putExtra(BksConstants.EXTRA_STATE, BksConstants.ADD);
				startActivityForResult(iA, BksConstants.REQUEST_ADD_FACILITY);
				break;
			// case BksConstants.EDIT:
			// Intent iE = new Intent(PPostOffer.this, DiaFacility.class);
			// iE.putExtra(BksConstants.EXTRA_STATE, BksConstants.EDIT);
			// if (lsvFacilitiesSelectPos > 0) {
			// iE.putExtra(BksConstants.EXTRA_FACILITY,
			// lstBeds.get(lsvBedSelectPos - 1));
			// startActivityForResult(iE, BksConstants.REQUEST_EDIT_BED);
			// }
			// break;
			case BksConstants.DELETE:
				if (lsvFacilitiesSelectPos > 0) {
					lstFacilities.remove(lsvFacilitiesSelectPos - 1);
					PFacilityAdapter faAdap = new PFacilityAdapter(
							getApplicationContext(), lstFacilities);
					lsvFacilities.setAdapter(faAdap);
				}
				break;
			case BksConstants.CLEAR:
				AlertDialog dialog = Dialog.getYesNoDialog(PPostOffer.this,
						"Do you really want to clear?");
				dialog.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface dialog) {
						clearFacilities();
					}
				});
				dialog.show();
				break;
			default:
				break;
			}

		}

	}

	private void clearBeds() {
		lstBeds = new ArrayList<QuoteBed>();
		PBedAdapter adap = new PBedAdapter(this, lstBeds);
		lsvBeds.setAdapter(adap);
	}

	private void clearFacilities() {
		lstFacilities = new ArrayList<QuoteFacility>();
		PFacilityAdapter adap = new PFacilityAdapter(getApplicationContext(),
				lstFacilities);
		lsvFacilities.setAdapter(adap);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case BksConstants.REQUEST_ADD_BED:
				// Get bed
				QuoteBed bed = (QuoteBed) data
						.getSerializableExtra(BksConstants.EXTRA_BED);
				if (bed != null) {
					// Check exist bed
					boolean isExist = false;
					for (int i = 0; i < lstBeds.size(); i++) {
						if (lstBeds.get(i).getName()
								.equalsIgnoreCase(bed.getName())) {
							isExist = true;
							break;
						}
					}
					if (isExist) {
						Toast.makeText(this, "Bed exist in available list",
								Toast.LENGTH_SHORT).show();
						return;
					}
					lstBeds.add(bed);
					PBedAdapter adap = new PBedAdapter(this, lstBeds);
					lsvBeds.setAdapter(adap);
				}

				break;
			case BksConstants.REQUEST_EDIT_BED:
				QuoteBed bedE = (QuoteBed) data
						.getSerializableExtra(BksConstants.EXTRA_BED);
				if (bedE != null) {
					// Check exist bed
					boolean isExist = false;
					int count = 0;
					for (int i = 0; i < lstBeds.size(); i++) {
						if (lstBeds.get(i).getName()
								.equalsIgnoreCase(bedE.getName())) {
							isExist = true;
							count++;
						}
					}
					if (count > 1) {
						Toast.makeText(this, "Bed exist in available list",
								Toast.LENGTH_SHORT).show();
						return;
					}
					lstBeds.set(lsvBedSelectPos, bedE);
					PBedAdapter adap = new PBedAdapter(this, lstBeds);
					lsvBeds.setAdapter(adap);
				}

				break;
			case BksConstants.REQUEST_ADD_FACILITY:
				QuoteFacility fA = (QuoteFacility) data
						.getSerializableExtra(BksConstants.EXTRA_FACILITY);
				if (fA != null) {
					// Check exist bed
					boolean isExist = false;
					for (int i = 0; i < lstFacilities.size(); i++) {
						if (lstFacilities.get(i).getId() == fA.getId()) {
							isExist = true;
							break;
						}
					}
					if (isExist) {
						Toast.makeText(this,
								"Facility exist in available list",
								Toast.LENGTH_SHORT).show();
						return;
					}
					lstFacilities.add(fA);
					PFacilityAdapter adap = new PFacilityAdapter(this,
							lstFacilities);
					lsvFacilities.setAdapter(adap);
				}

				break;
			default:
				break;
			}
		}
	}

	private String parseInfo() {
		String str = "";
		float star = rtbQuality.getRating();
		if (star == 0) {
			str = "Select your number star.";
		}
		BigDecimal price = new BigDecimal(0);
		if (str.length() == 0) {
			if (txtPrice.getText().toString().trim().length() == 0) {
				str = "Price is empty.";
			}
		}
		if (str.length() == 0) {
			price = new BigDecimal(txtPrice.getText().toString().trim());
			if (price.compareTo(new BigDecimal(0)) < 0) {
				str = "Price less than 0.";
			}
		}
		Map<String, Integer> mapBeds = new HashMap<String, Integer>();
		if (str.length() == 0) {
			if (lstBeds.size() == 0) {
				str = "Beds list is empty.";
			}
		}
		String beds = "";
		for (int i = 0; i < lstBeds.size(); i++) {
			mapBeds.put(lstBeds.get(i).getName(), lstBeds.get(i).getQuantity());
		}
		beds = JsonUtils.gson.toJson(mapBeds);

		int[] facilitiesArr = new int[lstFacilities.size()];
		for (int i = 0; i < lstFacilities.size(); i++) {
			facilitiesArr[i] = lstFacilities.get(i).getId();
		}
		if (str.length() == 0) {
			currentOffer.setBeds(mapBeds);
			currentOffer.setStar(star);
			currentOffer.setPrice(price.floatValue());
			currentOffer.setRoomtype(((QuoteRoomType) spnRoomType
					.getSelectedItem()).getId());
			currentOffer.setFacility(facilitiesArr);
		}

		return str;
	}
}
